package com.eastseeway.radioproject.main;


import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Observer;

import com.eastseeway.radioproject.BuildConfig;
import com.eastseeway.radioproject.OperationHoursService;
import com.eastseeway.radioproject.R;
import com.eastseeway.radioproject.base.BaseActivity;
import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.calibration.CalibrationActivity;
import com.eastseeway.radioproject.config.ConfigActivity;
import com.eastseeway.radioproject.debug.DebugActivity;
import com.eastseeway.radioproject.engineer.EngineerActivity;
import com.eastseeway.radioproject.entities.MessageEvent;
import com.eastseeway.radioproject.databinding.ActivityMainBinding;
import com.eastseeway.radioproject.gmn.NPActivity;
import com.eastseeway.radioproject.radio.HandleRadioActivity;
import com.eastseeway.radioproject.setting.SettingActivity;
import com.eastseeway.radioproject.tcp.TcpCallback;
import com.eastseeway.radioproject.utils.CommandGenerator;
import com.eastseeway.radioproject.utils.SPHelper;
import com.eastseeway.radioproject.utils.TimeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import struct.StructException;


public class MainActivity extends BaseActivity<ActivityMainBinding,MainViewModel> {
//    防止同时点击两个按钮
    private boolean isClickHandled = false;
    private final Observer<DeviceStatus> deviceStatusObserver = status -> {
        // 原有处理逻辑
        if (status.isDetectingHandles()) {
            mViewModel.getInfoContent().setValue("正在检测手具，请等待...");
        }else {
            if (status.isAllHandleOffline()) {
                mViewModel.getInfoContent().setValue("请插入手柄!");
            }else {
                mViewModel.getInfoContent().setValue("");
            }
        }
        EventBus.getDefault().postSticky(new MessageEvent(Const.EVENTBUS_HANDLE_STATE, status));
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @SuppressLint("ClickableViewAccessibility")
    protected void initEvent() {
        mBinding.setMViewModel(mViewModel);
        long operationHours = SPHelper.getOperationHours(getBaseContext());

        mBinding.back.setOnClickListener(v->{finish();playClickSound();});
        mBinding.mainTotalTime.setText(TimeUtils.getDiffTime(operationHours));



        mBinding.mainRadioButton.setOnClickListener(v->{
            if (isClickHandled) return;
            isClickHandled = true;
            playClickSound();
            mViewModel.sendHandleMessageToSwitchBoard((byte) 1);
            startActivity(new Intent(this, HandleRadioActivity.class));
        });
        mBinding.mainMnButton.setOnClickListener(v->{
            if (isClickHandled) return;
            isClickHandled = true;
            playClickSound();
            mViewModel.sendHandleMessageToSwitchBoard((byte) 0);
            startActivity(new Intent(this, NPActivity.class));
        });

//        Intent intent = new Intent(this, OperationHoursService.class);
//        bindService(intent,mServiceConnection,BIND_AUTO_CREATE);

    }

    @Override
    protected void loadData() {
//        boolean isTcpConnected = isTcpConnected();
//        mBinding.mainInfo.setText(isTcpConnected ? "已连接" : "未连接");
        mViewModel.getDeviceInfo();
    }

    @Override
    protected void observeData() {
        mViewModel.getDeviceStatusMutableLiveData().observeForever(
                deviceStatusObserver
        );


        mBinding.versionCodeTv.setText("软件完整版本：V1.0.0.0");
        mBinding.versionCodeTv.setOnClickListener(v->{
            continuousClick();
        });
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            OperationHoursService.InnerBinder binder = (OperationHoursService.InnerBinder) service;
            binder.addTimeChangeObserver(totalTime -> {
                mBinding.mainTotalTime.setText(totalTime);
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected Class<MainViewModel> getVMClass() {
        return MainViewModel.class;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OnEvent(MessageEvent messageEvent){
        int code = messageEvent.getCode();
        if (code == Const.TCP_CONNECT_STATUS) {
            TcpCallback.ConnectionState state = (TcpCallback.ConnectionState) messageEvent.getData();
            if (state == TcpCallback.ConnectionState.DISCONNECTED) {
                mBinding.tcpConnectState.setVisibility(View.VISIBLE);
            }else {
                mBinding.tcpConnectState.setVisibility(View.GONE);
            }
        }else if (code == Const.ADDRESS_FROM_HANDLE_1_DATA_1){
//            每次收到手柄1的信号后，移除上次的计时任务，开启新的计时任务
            mViewModel.processDataFrame(Const.ADDRESS_FROM_HANDLE_1_DATA_1);
        }else if (code == Const.ADDRESS_FROM_HANDLE_2_DATA_1){
//            每次收到手柄1的信号后，移除上次的计时任务，开启新的计时任务
            mViewModel.processDataFrame(Const.ADDRESS_FROM_HANDLE_2_DATA_1);
        }
    }

    final static int COUNTS = 5;// 点击次数
    final static long DURATION = 1000;// 规定有效时间
    long[] mHits = new long[COUNTS];
    private void continuousClick() {
        //每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
            mHits = new long[COUNTS];//重新初始化数组
            showListDialog();
        }
    }

    private void showListDialog(){
        final String[] items = {"设置","数据", "标定", "电极信息录入"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setCancelable(false);
        alertBuilder.setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss());
        alertBuilder.setItems(items, (dialogInterface, i) -> {
            switch (i) {
//                基础设置界面
                case 0: startActivity(new Intent(this, ConfigActivity.class));break;
//                数据展示界面
                case 1: startActivity(new Intent(this, EngineerActivity.class));break;
//                电压标定界面
                case 2: startActivity(new Intent(this, CalibrationActivity.class));break;
//                电极信息录入界面
                case 3: startActivity(new Intent(this, DebugActivity.class));break;
            }
            dialogInterface.dismiss();
        });
        alertBuilder.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mViewModel.getDeviceStatusMutableLiveData().removeObserver(deviceStatusObserver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isClickHandled = false;
    }
}